import { ref, onUnmounted, onMounted, reactive } from 'vue';  
import { vipServer } from "@/common/index";

export function useLottery() {
	const prize = ref([]); // 奖品列表
	// 索引为第四个位置的控制，防止开始抽奖按钮
	const sortPrize = ({arr, insertIndex = 3}) => {
		let newARR = [];
		let newVal = ""
		arr.forEach((item, i) => {
		  if(i === insertIndex){
		    newARR.push(item) 
		    newARR.push(newVal)
		  }else {
		     newARR.push(item)
		  }
		})
		return newARR
	}
	// 获取奖品列表
	const prizeList = async () => {
		try{
			const { data, status } = await vipServer.prizeList()
			if(status === "200" || status === "400"){
				const res = sortPrize({arr: data})
				prize.value = res
				// state.cycle = res[0]['rewardDay']
				// console.log("prize.value", prize.value)
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	onMounted(() => {
		prizeList()
	})
	
	const state = reactive({
	  cycle: 0,
	  countdown: 100, // 剩余时间  
	  isCounting: false, // 是否正在倒计时  
	  // current: prize.value[0]["rewardDay"]
	  // canSendAgain: false, // 是否可以重新发送验证码  
	}); 
	// 定时器引用
	let timer = null;  
	
	const runCycleIndex = () => {
		const order = [0,1,2,5,8,7,6,3]; // 高亮顺序索引
		const index = order.findIndex(item => item === state.cycle);
		if(index === order.length - 1){
			state.cycle = order[0]
		}else {
			state.cycle = order[index + 1]
		}
	}
	
	// 当前运行所在的块正好和传进来的值相同，也就是说明现在选中的就是抽奖抽中的，可以停止定时器了
	const indexIsCurrent = (rewardDay) => {
		const index = state.cycle
		return  prize.value[index]['rewardDay'] === rewardDay
	}
	// 运行10秒之后，如论哪次匹配上就终止
	const onEnd = (rewardDay) => {
		return state.countdown < 90 && (indexIsCurrent(rewardDay))
	}
	
	let speed = 200
	// 清除定时器
	const clearnTimer = () => {
		// 倒计时结束
		clearTimeout(timer)
		timer = null;
		state.countdown = 100
		state.isCounting = false;  
		speed = 200
	}
	
	const moveSpeed = () => {
		return Math.ceil((speed / 2)) + speed
	}
	// 开始运动
	const startMove = (rewardDay, callback) => {
		console.log('进入定时器', state)
		if(state.isCounting) return
		state.isCounting = true
		timer = setInterval(() => {
			if(state.countdown > 0) {
				state.countdown--;
				moveSpeed()
				runCycleIndex()
				if(onEnd(rewardDay)){
					clearnTimer()
					callback?.()
				}
			}else{
				clearnTimer()
				callback?.()
			}
		}, speed)
	}
	
	
	function stop() {  
	  if (timer) {  
	    clearInterval(timer);  
	    timer = null;  
		state.countdown = 100
	    state.isCounting = false;  
		speed = 200
	  }  
	}  
	
	// 重置，又是从第0个开始走动画
	function resetIndex(){
		 state.cycle = 0
	}
	
	// 组件卸载时清除定时器
	onUnmounted(() => {  
	  stop();  
	});  
	
	
	// 公开的方法
	return {
		state,
		clearnTimer,
		startMove,
		resetIndex
	}
}